package com.achao.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: achao
 * @DateTime: 2022/7/24 10:37
 * @Description: TODO
 */
public class CheckUtils {
    /**
     * 手机正则表达式验证
     *
     * @param phone
     * @return
     */
    public static boolean isPhone(String phone) {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        if (phone.length() != 11) {
            System.out.println("手机号应为11位数");
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
            if (!isMatch) {
                System.out.println("请填入正确的手机号");
            }
            return isMatch;
        }

    }

    /**
     * 身份证校验，支持15位和18位身份证校验
     *
     * @param idNumber 身份证号
     * @return true：校验通过  false：校验未通过
     */
    public static boolean checkIdNumber(String idNumber) {
        if (idNumber == null || "".equals(idNumber)) {
            return false;
        }
        String regularExpression = "(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|" +
                "(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)";

        boolean matches = idNumber.matches(regularExpression);
        // 判断第18位校验值
        int idNumberLength = 18;
        if (matches && idNumber.length() == idNumberLength) {
            try {
                char[] charArray = idNumber.toCharArray();
                // 前十七位加权因子
                int[] idCardWi = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
                // 这是除以11后，可能产生的11位余数对应的验证码
                String[] idCardY = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};
                int sum = 0;
                for (int i = 0; i < idCardWi.length; i++) {
                    int current = Integer.parseInt(String.valueOf(charArray[i]));
                    int count = current * idCardWi[i];
                    sum += count;
                }
                char idCardLast = charArray[17];
                int idCardMod = sum % 11;
                return idCardY[idCardMod].equalsIgnoreCase(String.valueOf(idCardLast));

            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return matches;
    }

    /**
     * 验证邮箱
     *
     * @param email 邮箱
     * @return true：校验通过  false：校验未通过
     */
    public static boolean checkEmail(String email) {
        if (email == null || "".equals(email)) {
            return false;
        }
        String regularExpression = "^([a-z0-9A-Z]+[-|_.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        try {
            return email.matches(regularExpression);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
